package com.example.springmvc_exception.通过注解实现全局异常;


import com.example.springmvc_exception.BusinessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * SpingMVC提供的第三种种全局异常处理方式
 * 1）@ControllerAdvice +@ExceptionHandler
 * 2）@RestControllerAdvice +@ExceptionHandler
 *      @RestControllerAdvice ==@Controller +@ResponseBody 返回JSON的数据格式，绕开视图解析器
 */
@ControllerAdvice
public class 全局异常处理器1 {

    /*这个是返回页面的时候*/
    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception e){
        ModelAndView modelAndView = new ModelAndView();
        /*设置错误页面*/
        modelAndView.setViewName("error");
        /*判断异常类型*/
        if(e instanceof BusinessException){
            BusinessException ex=(BusinessException)e;
            modelAndView.addObject("msg", "系统繁忙，请稍后再尝试~");
        }
        modelAndView.setView(new MappingJackson2JsonView());
        return modelAndView;
    }


}